import re

# from django.contrib.auth.hashers import check_password
from django.contrib.auth.handlers.modwsgi import check_password

from users.models import UserProfile
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.mixins import LoginRequiredMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

class SecretOauth(object):
    # 加密
    def dumps(self, content_dict):
        # 1.根据 签名(secret_key) 创建序列化对象
        serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=24 * 15 * 60)
        # 2. 通过 dumps方法 加密数据
        result = serializer.dumps(content_dict)
        # 3. result是bytes类型转换成 str
        return result.decode()

    # 解密
    def loads(self, content_dict):
        # 1.根据 签名(secret_key) 创建序列化对象
        serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=24 * 15 * 60)
        # 2. 通过 loads方法 解密数据
        result = serializer.loads(content_dict)
        # 3. 返回解密完毕数据
        return result


# 重写authenticate方法
class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self,request,username=None,password=None,**kwargs):
        if re.match('^1[3-9]\d{9}$', username):
           user = UserProfile.objects.get(mobile=username)
        else:
           user = UserProfile.objects.get(username=username)

        if user and user.check_password(password):
            return user
